const PAGE_SIZE_DEFAULT = 10
const PAGE_NUM_DEFAULT = 1
export default {
  /**
   * 从filterForm中获取筛选项
   */
  setTableFilter () {
    const self = this
    const baseUrl = self.baseUrl
    if (baseUrl) {
      console.log('vue-mixin: mounted function')
      let urlQuery = self.$route.query
      if (urlQuery && Object.keys(urlQuery).length > 0) {
        urlQuery = JSON.parse(JSON.stringify(urlQuery))

        for (let key in urlQuery) {
          // 如果筛选项存在
          if (typeof (this.filterForm[key]) !== 'undefined') {
            // 如果定义了筛选项的类型
            if (this.filterType && this.filterType[key]) {
              if (this.filterType[key] === 'array' && typeof (urlQuery[key]) === 'string') {
                this.filterForm[key] = [urlQuery[key]]
              } else if (this.filterType[key] === 'boolean' && typeof (urlQuery[key]) === 'string') {
                this.filterForm[key] = urlQuery[key] === 'true'
              }
            } else {
              this.filterForm[key] = urlQuery[key]
            }
          }
        }
      }

      if (urlQuery.pageNumber) {
        self.tableData.pageNumber = urlQuery.pageNumber ? parseInt(urlQuery.pageNumber) : PAGE_NUM_DEFAULT
      }
      if (urlQuery.pageSize) {
        self.tableData.pageSize = urlQuery.pageSize ? parseInt(urlQuery.pageSize) : PAGE_SIZE_DEFAULT
      }

      self.setFilter()
    }
  },
  resetFilter (filters = {}) {
    const self = this
    for (let f in self.filterForm) {
      self.filterForm[f] = null
    }
    self.setUrlFilters(filters)
  },
  setFilter () {
    const self = this
    self.setUrlFilters(self.getFilters())
  },
  getFilters: function () {
    const s = {}
    const self = this
    let filters = self.filterForm
    const invisible = ['vendorId']
    for (const f in filters) {
      if (invisible.includes(f)) {
        continue
      }
      let filter = filters[f]
      if (filter) {
        if (typeof (filter) === 'number' || typeof (filter) === 'string' || typeof (filter) === 'boolean') {
          s[f] = filter
          continue
        }
        if (typeof (filter) === 'object' && filter !== null) {
          const match = JSON.stringify(filter)
          if (match.indexOf('000Z') >= 0) {
            const dt = new Date(filter)
            s[f] = [dt.getFullYear(), dt.getMonth() + 1, dt.getDate()].join('-').replace(/(?=\b\d\b)/g, '0')
          } else {
            s[f] = filter
          }
        }
      }
    }
    if((!s.createTimeStart&&s.createTimeEnd)||(!s.uptTimeStart&&s.uptTimeEnd)){
      this.$message.warning('开始时间不能为空')
      return false
    }else if((!s.createTimeEnd&&s.createTimeStart)||(!s.uptTimeEnd&&s.uptTimeStart)){
      this.$message.warning('结束时间不能为空')
      return false
    }
    return s
  },
  setUrlFilters: function (filters) {
    if(!filters) return
    console.log('vue-mixin: setUrlFilters function')
    const self = this
    filters.pageNumber = filters.pageNumber ? filters.pageNumber : self.tableData.pageNumber
    filters.pageSize = filters.pageSize ? filters.pageSize : self.tableData.pageSize
    self.$router.push({path: self.$route.path, query: filters})
    self.fetchTableData(filters)
  },
  fetchTableData (options = {}) {
    const self = this
    const baseUrl = self.baseUrl
    options.pageNumber = options.pageNumber ? options.pageNumber : this.tableData.pageNumber ? this.tableData.pageNumber : PAGE_NUM_DEFAULT
    options.pageSize = options.pageSize ? options.pageSize : this.tableData.pageSize ? this.tableData.pageSize : PAGE_SIZE_DEFAULT
    // options.orderBy = this.filterForm && this.filterForm.orderBy ? this.filterForm.orderBy : ''
    if (baseUrl) {
      options.loading = true
      self.$get(baseUrl, options).then((res) => {
        self.tableData = {
          lists: res.content ? res.content : [],
          pageSize: res.size ? res.size : PAGE_SIZE_DEFAULT,
          pageNumber: res.requestPager ? res.requestPager : PAGE_NUM_DEFAULT,
          total: res.totalElements ? res.totalElements : 0
        }

        self.afterFetchTableData && self.afterFetchTableData()
      })
    }
  },
  // 排序数据
  handle_table_sort_change ({column, prop, order}) {
    console.log(column, prop, order)
    let sortType = ''
    if (order === 'ascending') {
      sortType = `${prop} asc`
    } else if (order === 'descending') {
      sortType = `${prop} desc`
    }
    this.filterForm.orderBy = sortType
    this.setFilter()
  },
  // 分页获取数据，先拿到筛选项的数据，再处理分页
  fetchWithPagination: function (currentPage) {
    console.log('vue-mixin: fetchWithPagination function')
    const self = this
    let urlQuery = self.getFilters()
    urlQuery.pageNumber = currentPage
    if (self.tableData.total) {
      self.setUrlFilters(urlQuery)
    }
  },
  fetchWithPageSize: function (pageSize) {
    console.log('vue-mixin: fetchWithPageSize function')
    const self = this
    self.tableData.pageSize = pageSize
    self.setFilter()
  },
  // **************************************华丽的分割线*********************************************/
  // 列表数据的格式化项
  // 格式化时间 DateTime 兼容 Safari
  tableFormatDateTime (row, column, cellValue) {
    if (!cellValue) return '-'
    cellValue = cellValue.replace(new RegExp(/-/gm), '/')
    let dt = new Date(cellValue)

    return Utils.Time.format('yyyy-MM-dd hh:mm:ss', dt)
  },
  // 格式化时间 Date 兼容 Safari
  tableFormatDate (row, column, cellValue) {
    if (!cellValue) return '-'
    cellValue = cellValue.replace(new RegExp(/-/gm), '/')
    let dt = new Date(cellValue)

    return Utils.Time.format('yyyy-MM-dd', dt)
  },
  tableFormatNumber (row, column, cellValue) {
    return Utils.Number.format(cellValue)
  },
  tableFormatPercent (row, column, cellValue) {
    return Number(cellValue * 100).toFixed(2) + '%'
  },
  tableIsNull (row, column, cellValue) {
    if (cellValue) {
      return cellValue
    }
    return '-'
  }
}
